package com.fengye.security.security.filter;

import lombok.Data;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.authentication.AuthenticationProvider;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.authentication.dao.AbstractUserDetailsAuthenticationProvider;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.crypto.password.PasswordEncoder;

import java.util.List;

@Data
@Slf4j
public class JwtAuthenticationProvider implements AuthenticationProvider {
//    @Override
//    protected void additionalAuthenticationChecks(UserDetails userDetails, UsernamePasswordAuthenticationToken authentication) throws AuthenticationException {
//
//    }
//
//    @Override
//    protected UserDetails retrieveUser(String username, UsernamePasswordAuthenticationToken authentication) throws AuthenticationException {
//        return null;
//    }


    private List<UserDetailsService> userDetailsServiceList;

    @Override
    public Authentication authenticate(Authentication jwtAuthenticationToken) throws AuthenticationException {
        // TODO: 验证 token是否过期等。
        String username = jwtAuthenticationToken.getName();
        for (UserDetailsService userDetailsService : userDetailsServiceList) {
            try {
                UserDetails user = userDetailsService.loadUserByUsername(username);
                if (user == null) {
                    continue;
                }
                return new JwtAuthenticationToken(user.getUsername(), null, user.getAuthorities());
            } catch (UsernameNotFoundException e) {
                log.debug("当前 userDetailsService 并未找到用户，继续" );
            }
        }

        return jwtAuthenticationToken;
    }

    @Override
    public boolean supports(Class<?> authentication) {
        return JwtAuthenticationToken.class.isAssignableFrom(authentication);
    }
}
